package com.jspxcms.plug.web.back;

import com.jspxcms.common.orm.RowSide;
import com.jspxcms.common.web.Servlets;
import com.jspxcms.core.support.Constants;
import com.jspxcms.core.support.Context;
import com.jspxcms.plug.domain.PlugHospital;
import com.jspxcms.plug.domain.PlugHospitalDepartment;
import com.jspxcms.plug.service.PlugHospitalDepartmentService;
import com.jspxcms.plug.service.PlugHospitalService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefaults;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Map;

import static com.jspxcms.core.support.Constants.*;

@Controller
@RequestMapping("/plug/hospitaldepartment")
public class HospitalDepartmentController {
    private static final Logger logger = LoggerFactory
            .getLogger(HospitalDepartmentController.class);

    @RequiresPermissions("plug:hospitaldepartment:list")
    @RequestMapping("list.do")
    public String list(Integer hid, @PageableDefaults(sort = "id", sortDir = Direction.DESC) Pageable pageable,
                       HttpServletRequest request,HttpServletResponse response, org.springframework.ui.Model modelMap) {

        if (hid == null) {
            try {
                response.getWriter().write("<script>alert('请先选择所属医院');window.location.href='../hospital/list.do'</script>");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        Integer siteId = Context.getCurrentSiteId(request);
        Map<String, String[]> params = Servlets.getParameterValuesMap(request, Constants.SEARCH_PREFIX);

        params.put("EQ_hospital.id", new String[]{hid.toString()});
        PlugHospital hospital = hospitalService.get(hid);
        if (hospital != null) {
            modelMap.addAttribute("hospital", hospital);
        }
        Page<PlugHospitalDepartment> pagedList = service.findAll(siteId, params, pageable);
        modelMap.addAttribute("pagedList", pagedList);
        modelMap.addAttribute("hid", hid);
        return "plug/department/department_list";
    }

    @RequiresPermissions("plug:hospitaldepartment:create")
    @RequestMapping("create.do")
    public String create(Integer id, Integer hid, org.springframework.ui.Model modelMap) {
        if (id != null) {
            PlugHospitalDepartment bean = service.get(id);
            modelMap.addAttribute("bean", bean);
            if (hid == null) {
                hid = bean.getHospital().getId();
            }
        }
        modelMap.addAttribute(OPRT, CREATE);
        modelMap.addAttribute("hid", hid);
        return "plug/department/department_form";
    }

    @RequiresPermissions("plug:hospitaldepartment:edit")
    @RequestMapping("edit.do")
    public String edit(
            Integer id,
            Integer hid,
            Integer position,
            @PageableDefaults(sort = "id", sortDir = Direction.DESC) Pageable pageable,
            HttpServletRequest request, org.springframework.ui.Model modelMap) {
        Integer siteId = Context.getCurrentSiteId(request);
        PlugHospitalDepartment bean = service.get(id);
        Map<String, String[]> params = Servlets.getParameterValuesMap(request, Constants.SEARCH_PREFIX);
        RowSide<PlugHospitalDepartment> side = service.findSide(siteId, params, bean, position,
                pageable.getSort());
        modelMap.addAttribute("bean", bean);
        if (hid == null && bean != null && bean.getHospital() != null) {
            hid = bean.getHospital().getId();
        }
        modelMap.addAttribute("hid", hid);
        modelMap.addAttribute("side", side);
        modelMap.addAttribute("position", position);
        modelMap.addAttribute(OPRT, EDIT);
        return "plug/department/department_form";
    }

    @RequiresPermissions("plug:hospitaldepartment:save")
    @RequestMapping("save.do")
    public String save(@Valid PlugHospitalDepartment bean, Integer hid, String redirect,
                       HttpServletRequest request, RedirectAttributes ra) {
        if (hid != null) {
            Integer siteId = Context.getCurrentSiteId(request);
            PlugHospital hospital = new PlugHospital();
            hospital.setId(hid);
            bean.setHospital(hospital);
            service.save(bean, siteId);
            logger.info("save PlugHospitalDepartment, name={}.", bean.getfDepartmentName());
            ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
            if (Constants.REDIRECT_LIST.equals(redirect)) {
                ra.addAttribute("hid", hid);
                return "redirect:list.do";
            } else if (Constants.REDIRECT_CREATE.equals(redirect)) {
                ra.addAttribute("hid", hid);
                return "redirect:create.do";
            } else {
                ra.addAttribute("id", bean.getId());
                return "redirect:edit.do";
            }
        } else {
            ra.addAttribute("hid", hid);
            return "redirect:list.do";
        }
    }

    @RequiresPermissions("plug:hospitaldepartment:update")
    @RequestMapping("update.do")
    public String update(@ModelAttribute("bean") PlugHospitalDepartment bean,
                         Integer hid,
                         Integer position,
                         String redirect, RedirectAttributes ra) {
        PlugHospital hospital = new PlugHospital();
        hospital.setId(hid);
        bean.setHospital(hospital);
        service.update(bean);
        logger.info("update PlugHospitalDepartment, name={}.", bean.getfDepartmentName());
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        if (Constants.REDIRECT_LIST.equals(redirect)) {
            return "redirect:list.do";
        } else {
            ra.addAttribute("id", bean.getId());
            ra.addAttribute("position", position);
            return "redirect:edit.do";
        }
    }

    @RequiresPermissions("plug:hospitaldepartment:delete")
    @RequestMapping("delete.do")
    public String delete(Integer[] ids, RedirectAttributes ra) {
        PlugHospitalDepartment[] beans = service.delete(ids);
        for (PlugHospitalDepartment bean : beans) {
            logger.info("delete PlugHospitalDepartment, name={}.", bean.getfDepartmentName());
        }
        ra.addFlashAttribute(MESSAGE, DELETE_SUCCESS);
        return "redirect:list.do";
    }

    @ModelAttribute("bean")
    public PlugHospitalDepartment preloadBean(@RequestParam(required = false) Integer oid) {
        return oid != null ? service.get(oid) : null;
    }

    @Autowired
    private PlugHospitalService hospitalService;

    @Autowired
    private PlugHospitalDepartmentService service;
}
